home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8996 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  77 lines

  1. Path: crchh327.rich.bnr.ca!jobell
  2. From: jobell@bnr.ca (Bret Bieghler)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: To find the class of an object ??
  5. Date: 27 Feb 1996 20:21:08 GMT
  6. Organization: Bell-Northern Research Ltd.
  7. Message-ID: <4gvp3k$j1@crchh327.rich.bnr.ca>
  8. References: <4gvel6$4vg@cf01>
  9. NNTP-Posting-Host: crchh524.rich.bnr.ca
  10.  
  11. In article <4gvel6$4vg@cf01>, Didier BOLF <didier@cln46ib> wrote:
  12. >
  13. >Hi,
  14. >My problem:
  15. >I have a class A and a class B. The class B inherit the class A.
  16. >I have too: A tab[MAX]; 
  17. >In tab, I put objets of class A or B.
  18. >How compare two objects of tab to know if they are of the same class ??
  19. >and which class they belong to ??
  20. >Thanks to reply..
  21. >Didier.
  22. >Email: didier@cln46fw.der.edf.fr
  23. >
  24.  
  25. From Bruce Eckel's "Thinking in C++", page 721,
  26.  
  27. "Run-time type identification (RTTI) lets you find the exact type
  28. of an object when you have only a pointer or reference to the base
  29. type."
  30.  
  31. If your compiler supports RTTI look into this, or you can add
  32. RTTI member functions that return identifiers as to what type they
  33. are.
  34.  
  35. As in:
  36.  
  37. B myBObject;
  38. A* aPtr;
  39.  
  40. aPtr = &myBObject;
  41.  
  42. aPtr->whatType();
  43.  
  44. would print (or return) "I'm a B."
  45.  
  46. thus, you would have
  47.  
  48. class A
  49. {
  50.     virtual void whatType(void)
  51.     {
  52.         cout << "I'm an A." << endl;
  53.     }
  54. }
  55.  
  56. class B : public A
  57. {
  58.     void whatType (void)
  59.     {
  60.         cout << "I'm a B." << endl;
  61.     }
  62. }
  63.  
  64. hope this helps.
  65.  
  66. Joe
  67.  
  68. -- 
  69. Joseph A. Bell (NOT Bret Bieghler) jobell@bnr.ca
  70. Northern Telecom / Bell-Northern Research
  71. "What?  Evacuate now, in our moment of triumph?  Surely you overestimate their chances."
  72.